var headOffset=false;

$(document).ready(function(){
	if( typeof(json_data)!='undefined' ){
		window['programm']=prg_editor({
		  container:'#programm',
		  tpl:{
		    body:'#js_programm',
		    programm:'#js_programm',
		    week:'#js_week',
		    day:'#js_day',
		    ex:'#js_ex'
			},
		  data:json_data
		});
		if( programm )	programm.apply();
	}else alert('no json data');

  headOffset=$('#head_slide').offset().top;
	$(window).scroll(function(e){
	  if($(window).scrollTop()>=headOffset ){
	    if(!$('#container').hasClass('fixed')) $('#container').addClass('fixed');
		}else $('#container').removeClass('fixed');
	});
	
	change_tuner.add( init_editable );
	change_tuner.add( ex_add_clicks );
	change_tuner.apply();
	
	$('#button_save').addClass('gray');
	
	$('#features').change(function(){
	  alert('OK');
	  switchSaveBut();
	});
});

function switchSaveBut(){
	if(programm.somthingChanged) $('#button_save').removeClass('gray');
	else if( !$('#button_save').hasClass('gray') ) $('#button_save').addClass('gray');
}

function set_user(obj){
	programm.change('',{user:$(obj).val()});
}

function add_day_form(){
  if($('#day_add_form').is(':visible') ){
    $('#day_add_form').hide();
	  $('#add_day_link').show();
	}else{
	  $('#add_day_link').hide();
    $('#day_add_form').show().find('input').first().focus();
	}
}
function add_ex_form(after){
	remove_add_ex_form();
	after.after( $('#js_ex_add').html() );
	after.siblings('.sex').attr('id','ex_add_form');
	
	liveSearch.init( $('#ex_add_form') ,{
		attr_set:'placeholder,name,id',
		response_var:'block',
		search_url:'/ajax/',
		query_obj:{'fields':['block'], 'mode':'search_ex'},
		onInit:function(e){
		  $(e).focus();
		},
		onResponse:function( respJS,e ){
			$('ul:first li a',e.liveSearch.results).click(function(){
			  //Set values
			  var data={
			    'id': 'new_'+Math.floor(Math.random()*1000),
			    'lid': $(this).attr('rel'),
			    'ex_name': $(this).find('.name').text(),
			    'ex_img': $(this).find('.img').text(),
				};

				programm.add_ex( $('#ex_add_form').parents('.day').attr('rel'), data);
			  //Remove LS and editor
			  remove_add_ex_form();
				return false;
			});
		}
		//,onResponseText:'alert'
	});

	$('.editField').focus();
	
	return false;
}
function remove_add_ex_form(){
  liveSearch.remove('#ex_add_form');
  $('#ex_add_form').remove();
}

function show_editor(obj){
	//Убрать блок редактирования если есть
	if( $('.editBlock').get().length>0 ){
	  $('.editBlock .cancel').click();
	}
  //Если поле не редактируемое - все - куконь.
	if( !$(obj).hasClass('txt') ){display_error('Field not "txt" class');return false;}
	
	//Добавить контейнер хранилище результата, если нету
	if( $(obj).find('span').get().length<1 ) $(obj).html('<span>'+$(obj).html()+'</span>');
	
	//Запомнить ширину, и выставить явно
	var owidth=$(obj).width();
	$(obj).css('width',owidth+'px');

	if( $(obj).hasClass('name') ){
	  show_search_editor(obj);
	}else	show_txt_editor(obj);
}
var textareaFocus=false;
function show_txt_editor(obj){
  textareaFocus=false;
  var editorHTML='<div class="editBlock" style="width:'+$(obj).width()+'px"><i></i>';
  if($(obj).hasClass('big')){
    editorHTML+='<textarea class="editField" style="width:'+$(obj).width()+'px; height:'+$(obj).height()+'px">'+$('span',obj).html()+'</textarea>';
    textareaFocus=true;
  }else
		editorHTML+='<input type="text" class="editField" style="width:'+$(obj).width()+'px" value="'+$('span',obj).text()+'">';
		
	editorHTML+='<a href="#" class="apply">Apply <small>(Enter)</small></a>'+
		'<a href="" class="cancel">Cancel <small>(ESC)</small></a></div>';
		
	$(obj).addClass('active').append(editorHTML);
	$('.editField').focus();

	$('.editBlock .apply').click(function(){
	  //Сохранить изменения в память
	  var data={};
	  var prt=$(this).parents('.txt');
	  
	  switch(prt.data('format')){
	    case 'date': var value=convert_date($('.editField').val(),'store'); break;
	    default: var value=$('.editField').val();
		}
		var changing=prt.attr('rel')
		
	  data[ changing  ]=value;
	  var path='';
	  var t=$(this).parents('.ex'); if( t.get().length>0 ) path=t.first().attr('rel');
	  if(path==''){
	    var t=$(this).parents('.day'); if( t.get().length>0 ) path=t.first().attr('rel');
		}
	  if( programm.change(path,data)>0 ){
	    $(this).parents('.txt').children('span').first().html(
	      $('.editField').val()
			);
			
		  if( changing=='order' ){
		    programm.apply();
			}
		}
  	
		gotonext(1);
    return false;
	});
	$('.editBlock .cancel').click(function(){
	  $(this).parents('.txt').removeClass('active');
    $(this).parents('.editBlock').remove();
    return false;
	});
}
function show_search_editor(obj){
	var editorHTML='<div class="editBlock search" style="width:'+$(obj).width()+'px"><i></i><a href="#" class="cancel">cancel</a>'+
		'<input type="text" class="editField" style="width:'+$(obj).width()+'px" value="'+$('span',obj).text()+'"></div>';
	$(obj).addClass('active').append(editorHTML);
	
	$('.editBlock .cancel').click(function(){
	  liveSearch.remove('.editField');
	  $(this).parents('.txt').removeClass('active');
    $(this).parents('.editBlock').remove();
    return false;
	});
	
	liveSearch.init($('.editField')[0],{
		attr_set:'placeholder,name,id',
		response_var:'block',
		search_url:'/ajax/',
		query_obj:{'fields':['block'], 'mode':'search_ex'},
		onInit:function(e){
		  $(e).focus();
		},
		//make_query:function(ls_obj){return {'query':$(ls_obj).val()}},
		onResponse:function( respJS,e ){
			$('ul:first li a',e.liveSearch.results).click(function(){
			  var data={
			    ex_img:$(this).find('.img').text(),
			    ex_name:$(this).find('.name').text(),
			    lid:$(this).attr('rel'),
				};
			  
			  var path='';
			  var t=$(this).parents('.ex'); if( t.get().length>0 ) path=t.first().attr('rel');
			  if(path==''){
			    var t=$(this).parents('.day'); if( t.get().length>0 ) path=t.first().attr('rel');
				}
			  if( programm.change(path,data)>0 ){
					programm.somthingChanged=true;
					switchSaveBut();
				  var eobj=$(this).parents('.txt');
				  eobj.prev().text( $(this).attr('rel') );
				  eobj.find('.name').text( $(this).text() );
				}
			  //Remove LS and editor
			  $('.editBlock .cancel').click();
				programm.apply();
		    return false;
			});
		}
		//,onResponseText:'alert'
	});
	
	$('.editField').focus();
}

function init_editable(){
  $('.remove_day',this.container).unbind('click').click(function(){
    if( !confirm("Are you shure? \n Removing day removes all exercises!") ) return false;
    var ind=$(this).parents('.day').attr('rel');
		programm.remove_day(ind);
		return false;
	});
  $('.remove_ex',this.container).unbind('click').click(function(){
    if( !confirm("Are you shure?") ) return false;
    var ind=$(this).parents('.ex').attr('rel').split('/');
		programm.remove_ex(ind[0],ind[1]);
		return false;
	});

	$('.txt:not(.done)',this.container).each(function(elnum){
	  $(this).attr('data-zindex',elnum).click(function(){
	    if( !$(this).hasClass('active') ) show_editor(this);
		}).addClass('done');
	});
	$('.open_close',this.container).unbind('click').click(function(){
	  var el=$(this).parents('.day');
	  if(el.hasClass('open')) el.removeClass('open');
	  else el.addClass('open');
	  return false;
	});
	$(window).unbind('keydown').keydown(function(e){
		if($('.editField').get().length>0 ){
		  var code=false;
		  if(e=='next'){ code=9; alert('YAYA!');}
		  else	code= e.keyCode || e.which;
		  
			switch(code){
			  case 38://UP arr
			  case 40: //DOWN arr
			    if( textareaFocus ) return true;
			    var t=$('.editField').parents('.txt').attr('class');
			    t=t.replace('txt','').replace('done','').replace('active','').replace('  ','');
			    if( code==38 )
			    			var el=$('.editField').parents('.txt').parent().prev().find('.'+t);
			    else  var el=$('.editField').parents('.txt').parent().next().find('.'+t);
       $('.editField').blur();
					el.click();
					return false;
			    break;
			  case 27://Ecs
					//$('.editField').blur();
					$('.editBlock .cancel').click();
					return false;
					break;
				case 9://Tab
				  if(e.shiftKey || code==37) var it=-1; else var it=1;
				  gotonext(it);
					return false;
					break;
				case 13: //Enter
      		$('.editBlock .apply').click();
					return false;
				  break;
			}
		}
	});
}

function ex_add_clicks(){
	$('.add_ex_link:not(.done)',this.container).click(function(){
	  //alert('add ex');
	  add_ex_form($(this));
	  return false;
  }).addClass('done');
}

function gotonext(it){
      		var znext=parseInt( $('.editField').parents('.txt').attr('data-zindex') );
				  var tests=1000;
				  do{
				    znext+=it;
				    var next=$('.txt[data-zindex='+ znext +']');
				    tests--;
					}while( next && !next.is(':visible') && tests);
					$('.editBlock .cancel').click();
     			next.click();
}

function sort_days_func(a, b){
 	//alert( a.date+'<'+b.date+ (( a.date<b.date )?'true':'false') );
  if(a.date<b.date)	return -1;
  if(a.date>b.date)	return 1;
  return 0
}
function sort_ex_func(a,b){
  a.order=parseInt(a.order);
  b.order=parseInt(b.order);
  if(a.order<b.order)	return -1;
  if(a.order>b.order)	return 1; 
  //if(a.id<b.id)	return -1;
  //if(a.id>b.id)	return 1;
  return 0
}

var prg_editor=function(configprm){
  this.somthingChanged=false;
	this.data=false;
	this.config=false;
	this.container=false;
	this.tpl=false;
	this.back_index={ex:new Array(),day:new Array()};
	
	
	this.init=function(config){
	  if( !this.valid_dom(config) ) return false;
	  if( !this.set_data(config.data) ) return false;
	  
	  this.tpl=config.tpl;
	  $('#programmUser').val( this.data.user );
	  this.container=$(config.container);
	  return true;
	}

	this.valid_dom=function(){
	  return true;
	}
	this.valid_data=function(data){
	  return true;
	}
	this.set_data=function(data){
	  if(!this.valid_data(data)) return false;
	  this.data=data;
	  return true;
	}
	this.add_day=function(date){
	  if(!date){
	    display_error('Date not passed');
	    return false;
		}
		
		var tst_date=convert_date(date,'store');
	  for(var i=0,exists=false; i<this.data.days.length; i++){
	    if( this.data.days[i].date==tst_date ){
				exists=true; break;
			}
		}
		
		if(exists){
		  display_error('Date '+convert_date(date,'display')+' alredy exists');
		  return false;
		}
		
	  this.data.days.push({
			date:convert_date(date,'store'),
			col:0,
			dur:0,
      id:Math.floor( Math.random()*1000 ),
      is_new:true,
      ex:new Array()
		});
		this.somthingChanged=true;
		switchSaveBut();

		this.apply();
	}
	
	this.remove_day=function(day_ind){
    this.data.days.remove(day_ind);
		this.somthingChanged=true;
		switchSaveBut();
    this.apply();
	}

	this.add_ex=function(day_ind,data){
	  //var ordNum=this.data.days[day_ind].ex.length;
	  if( this.data.days[day_ind].ex.length )
			var ordNum=Math.max.apply(
				Math,
				this.data.days[day_ind].ex.map(function(o){return o.order;})
			)+1;
		else var ordNum=1;

	  this.data.days[day_ind].ex.push({
			id:'new_'+data.id,
			lid:data.lid,
			repl:0,
      steps:0,
      rest:0,
      comment:'',
      ex_name:data.ex_name,
      ex_img:data.ex_img,
      is_new:true,
      order:ordNum
		});
	  this.somthingChanged=true;
		switchSaveBut();

		this.apply();
	}
	
	this.remove_ex=function(day_ind,ex_ind){
    this.data.days[day_ind].ex.remove(ex_ind);
		this.somthingChanged=true;
		switchSaveBut();
    this.apply();
	}

	this.apply=function(){
	  var mem_opened=new Array();
	  $('.day.open',this.container).each(function(){
	    mem_opened.push( $(this).attr('id') );
		});
	  this.container.html('');
	
	  //Sort data
	  this.data.days.sort( sort_days_func );
	  //set container
	  if( $('#programm_'+this.data.id).get().length<1 ){
			this.container.html( $(this.tpl.body).html() );
			$('.programm',this.container).attr('id','programm_'+this.data.id);
			this.container_loc=$('#programm_'+this.data.id);
		}
		
		//set container data convert_date(input,mode,def)
		$('[rel="date"]',this.container_loc).html( convert_date(this.data.date,'display') );
		$('[rel="deadline"]',this.container_loc).html( convert_date(this.data.deadline,'display') );
		$('[rel="features"]',this.container_loc).html( this.data.features );
		$('[rel="pack"]',this.container_loc).html( this.data.pack );
		
		//wrap data days - detect weeks
		var index=new Array(),maxweek=0;
//console.log(this.data.days);
		for( var i=0; i< this.data.days.length; i++ ){
		  if(this.data.days[i].ex.length>0)
				this.data.days[i].ex.sort( sort_ex_func );
//alert( i+') '+this.data.days[i].date );

		  var tstweek=new Date(this.data.days[i].date).getWeek();

		  //Если следующая неделя - подставить дату предыдущей
		  maxweek=Math.max(maxweek,tstweek);
//alert(tstweek+' '+maxweek);
		  //Если недели нет - добавить
		  if( typeof(index[ tstweek ])=='undefined' ){
		    var weekObj=$($(this.tpl.week).html());
		    $(weekObj).attr('id','week_'+tstweek).find('.date_from').html(
		      convert_date( this.data.days[i].date ,'display')
				);
		    index[ tstweek ]= {obj:weekObj, days:new Array()};
			}

		  var day=$($(this.tpl.day).html());
			day.attr('id','day_'+this.data.days[i].id);
			day.attr('rel',i);
	  	day.find('[rel="id"]').html( this.data.days[i].id );
	  	
		  day.find('[rel="date"]').html(	convert_date(this.data.days[i].date,'display') );
		  day.find('[rel="dur"]').html(	this.data.days[i].dur	);
		  day.find('[rel="col"]').html(	this.data.days[i].col	);
		  
		  index[ tstweek ].days.push( {obj:day, exs:new Array()} );
		  var dayid=index[ tstweek ].days.length-1;
		  this.back_index.day[ this.data.days[i].id ]=i;

			//Перебираю упражнения
		  for(var j=0; j< this.data.days[i].ex.length; j++ ){
			  var ex=$( $(this.tpl.ex).html() );
			  ex.attr('id','ex_'+this.data.days[i].ex[j].id	);
			  ex.addClass( 'confirm_'+this.data.days[i].ex[j].confirm );
			  //ex.attr('rel', j	);
			  //Пусть в структуре для редактирования
			  ex.attr('rel', i+'/'+j);
			  
			  ex.find('.id').html(	this.data.days[i].ex[j].id	);
				ex.find('.lib').html(	this.data.days[i].ex[j].lid	);
				ex.find('.repl').html(	this.data.days[i].ex[j].repl	);
				ex.find('.steps').html(	this.data.days[i].ex[j].steps	);
				ex.find('.rest').html(	this.data.days[i].ex[j].rest	);
				ex.find('.comment').html(	this.data.days[i].ex[j].comment	);
				ex.find('.name').html(	this.data.days[i].ex[j].ex_name	);
				ex.find('.img').attr('src',	this.data.days[i].ex[j].ex_img	);
				ex.find('.order').html(	this.data.days[i].ex[j].order	);
				
        index[ tstweek ].days[ dayid ].exs.push( ex );
        //index[ tstweek ].days[ dayid ].exs[i]= ex ;
        this.back_index.ex[ this.data.days[i].ex[j].id ]=(i+'/'+j);
			}
		}

		//Подставить недель с готовыми днями
		for( var i=0; i<=index.length; i++ ){
		  if( !index[i] ) continue;
			for(var j=0; j<index[i].days.length; j++){
			  if( !index[i].days[j] ) continue;
			  for(var k=0; k<index[i].days[j].exs.length; k++){
			    if( !index[i].days[j].exs[k] ) continue;
			    //DOMбавить упражнение
			    index[i].days[j].obj.find('.exs').append( index[i].days[j].exs[k] );
			  }
			  //DOMбавить день
			  index[i].obj.find('.days').append( index[i].days[j].obj );
			}
			//DOMбавить дату завершения недели
			index[i].obj.find('.date_to').html( index[i].obj.find('.day:last .date').html() );
			//DOMбавить неделю
      $('.weeks',this.container_loc).append( index[i].obj );
		}
		delete index;
		change_tuner.apply();
		
		//open opened before
		for(var i=0; i<mem_opened.length; i++){
		  $('#'+mem_opened[i]).find('.open_close').click();
		}
		//console.log(this.back_index);
	}
	/******************************
	 *	Mathosd to apply changes in data structure
	 *	accept 2 params: path(slash  separated numIndexes or empty), data (hashObject of key:value) to change
	 *	returns false or "affected rows"
	*********************************/
	this.change=function(path,data){
	  //Ефлс есть путь - найти чуда редактировать
    var tpath=path.split('/');
    
    switch( tpath.length ){
      case 2:
        var cur=this.data.days[ tpath[0] ].ex[ tpath[1] ];
				break;
      case 1: 
        if( tpath[0]!='' )
      		var cur=this.data.days[ tpath[0] ];
      	else
      	  var cur=this.data;
				break;
      default:
				return false;
		}

		delete tpath;
		var changes=0;
		for(var i in data){
		  if( typeof( cur[ i ] )=='undefined' ) continue;
		  if( cur[ i ] == data[ i ] ) continue;
		  cur[ i ] = data[ i ];
		  changes++;
		}
		if(changes>0){
		  this.somthingChanged=true;
			switchSaveBut();
		}
		return changes;
	}
	
	this.compile=function(){
	  return false;
		//Собираю данные программы
	  var cont=this.container_loc.children('.head');

		this.data.date=convert_date($('.date',cont).text(),'store');
		this.data.deadline=convert_date($('.deadline',cont).text(),'store');
		this.data.features=$('.features',cont).text();
		//Собираю данные дней
		var days=new Array();
		$('.day').each(function(){
			var cont=$(this).children('.head');
			var t={};
			t.id		=parseInt(	$('.id',cont).text()		);
			t.date	=convert_date($('.date',cont).text(),'store');
			t.dur		=(	$('.dur',cont).text()		);
			t.col		=(	$('.col',cont).text()		);
			t.ex=new Array();
			$('.exs .ex',this).each(function(){
			  var e={};
			  e.id		=parseInt(	$('.id',this).text()		);
			  e.lib		=parseInt(	$('.lib',this).text()		);
			  e.repl	=(	$('.repl',this).text()		);
			  e.steps	=(	$('.steps',this).text()		);
			  e.rest	=(	$('.rest',this).text()		);
			  e.comment	=(	$('.comm',this).text()		);
			  e.ex_name	=(	$('.name',this).text()		);
			  e.ex_image	=(	$('img',this).attr('src')		);
			  t.ex.push(e);
			  delete e;
			});
			days.push(t);
			delete t;
		});
		this.data.days=days;
		
		delete days;
		//console.log('after',this.data);
	}
	
	this.save=function(){
	  if( !this.somthingChanged ){
			display_error('<strong>Warning</strong> Nothing to save');
			return false;
		}
		var fileObj=$('#features').get()[0];
		
		make_request(
			{
			  'mode':'programm_save',
			  'data':this.data,
			  'file':fileObj
			},
			function(req){
				if( req.responseJS.block=='success' ){
				  this.data=JSON.parse(req.responseJS.json);
          display_message('<strong>Success</strong> Data saved');
          programm.somthingChanged=false;
          switchSaveBut();
          this.apply();
				}else{
				  display_error('<strong>Error!</strong> '+req.responseJS.error );
				}
			}
		);
	}
	this.remove=function(){
	
	  var dt={id:this.data.id};
		make_request(
			{
			  'mode':'programm_remove',
			  'data':dt
			},
			function(req){
				if( req.responseJS.block=='success' ){
          display_message('<strong>Success</strong> Programm removed');
          setTimeout(function(){
            document.location.assign('/manage/users/'+this.data.user );
					},1500);
				}else{
				  display_error('<strong>Error!</strong> '+req.responseJS.error );
				}
			}
		);
	}

	//INIT
	if(!this.init(configprm))return false;
	return this;
};

/********************************
 *  HElpers
 ********************************/
Date.prototype.getWeek = function() {
  //var onejan = new Date(this.getFullYear(),0,1);
  var onejan = new Date(2010,0,1);
  return Math.ceil( ( ((this - onejan) / 86400000) + onejan.getDay()+1 ) / 7 );
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};